<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/11/16
 * Time: 14:11
 */
namespace App\Service\Admin;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Http\Model\Mysql\AnchorModel;
use App\Http\Model\Mysql\BoxModel;
use App\Http\Model\MongoDB\LiveList;
use App\Http\Model\Mysql\OrderModel;
use App\Service\Live\AlterService;
use App\Service\Live\ClientService;
use App\Service\Live\AnchorService as AnchorLiveService;
use App\Service\Live\OperateService;
use App\Utils\WechatUtil;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;

class RoomService extends BaseService
{
    /**
     * 直播间列表
     * @param int $status
     * @param int $pub_status   0  正常       1   不公开     3   已下架
     * @param int|null $limit
     * @param int $page
     * @return array
     */
    public function roomList(int $status = -1, int $pub_status = -1, int $limit = null, int $page = 1)
    {
        $limit  =   empty($limit) ? self::PAGE_LIMIT : $limit;

        if ($status != -1) {
            $where['Status']    =   $status;
        }

        if ($pub_status != -1) {
            $where['PubStatus'] =   $pub_status;
        }

        $model  =   LiveList::query();
        if (!empty($where)) {
            $model  =   $model->where($where);
        }

        $client =   new ClientService();
        $count  =   $model->count();
        $list   =   $model->offset(($page - 1) * $limit)->limit($limit)->orderBy('Id', 'desc')->select(['Id', 'Title', 'StartTime', 'PlanedStartTime', 'EndTime', 'RTMPPullUrl', 'FLVPullUrl', 'HLSPullUrl', 'Status', 'PlanedEndTime', 'PubStatus', 'Desc', 'HostName'])
                    ->get()->each(function (&$item) use ($client){
                        $item->StartTime    =   Carbon::createFromTimestamp($item->StartTime / 1000)->toDateTimeString();
                        $item->PlanedStartTime  =   Carbon::createFromTimestamp($item->PlanedStartTime / 1000)->toDateTimeString();
                        $item->EndTime      =   Carbon::createFromTimestamp($item->EndTime / 1000)->toDateTimeString();
                        $item->PlanedEndTime   =   Carbon::createFromTimestamp($item->PlanedEndTime / 1000)->toDateTimeString();
                        $item->Viewers      =   $client->getUserWatch($item->Id) ?? 0;
                        $item->ActualViewers=   $client->getVisitNum($item->Id) ?? 0;
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'list'  =>  $list->toArray(),
                'pages' =>  ceil($count / $limit),
                'current'=> $page
            ]];
        }
    }

    /**
     * 房间ID详情
     * @param int $room_id
     * @return array
     */
    public function roomDetail(int $room_id)
    {
        $result =   LiveList::where(['Id' => $room_id])->first();
        if (empty($result)) {
            return [false, '直播间不存在'];
        } else {
            return [true, $result];
        }
    }

    /**
     * 生成二维码
     * @param int $room_id
     * @param int $box_id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function roomCode(int $room_id, int $box_id)
    {
        $box_unique   =   $box_id != 0 ? BoxModel::where(['id' => $box_id])->value('unique_id') : '';
        $admin_info   =   request()->post('admin_user');

        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'live'], $admin_info['user_id']);  //, 'page' => 'pages/live/detail?room_id=' . $room_id . '&box_id=' . $box_unique
        if ($flag && isset($result['img_path'])) {
            return [true, file_get_contents($result['img_path'])];
        } else {
            return [false, '二维码生成失败'];
        }
    }

    /**
     * 分享直播间
     * @param int $room_id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function roomShare(int $room_id)
    {
        $admin_info   =   request()->post('admin_user');
        $room_info    =   LiveList::where(['Id' => $room_id])->select(['Title', 'PlanedStartTime', 'MainImg'])->first();
        if (empty($room_id)) {
            return [false, '直播间不存在'];
        }

        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'share'], $admin_info['user_id']);  //, 'page' => 'pages/live/detail?room_id=' . $room_id
        if ($flag && isset($result['img_path'])) {
            return [true, [
                'code_img'  =>  $result['img_path'],
                'title'     =>  $room_info['Title'],
                'start_time'=>  Carbon::createFromTimestamp($room_info['PlanedStartTime'])->toDateTimeString(),
                'main_img'  =>  $room_info['MainImg']
            ]];
        } else {
            return [false, '二维码生成失败'];
        }
    }

    /**
     * 直播间下架
     * @param int $room_id
     * @param int $live_type
     * @return array
     */
    public function roomOffline(int $room_id, int $live_type = 1)
    {
        $live_pub   =   LiveList::NORMAL_PUB;
        $pub_status =   LiveList::where(['Id' => $room_id])->value('PubStatus');
        switch ($live_type) {
            case 1:             //公开
                $live_pub   =   LiveList::NORMAL_PUB;
                break;

            case 2:             //不公开
                $live_pub   =   LiveList::HIDE_PUB;
                break;

            case 3:             //下架
                $live_pub   =   LiveList::OFFLINE_PUB;
                break;
        }

        if ($pub_status == $live_pub) {
            return [false, '操作错误'];
        }

        $result =   LiveList::where(['Id' => $room_id])->update(['PubStatus' => $live_pub]);
        if ($result) {
            return [true, '操作成功'];
        } else {
            return [false, '操作失败'];
        }
    }

    /**
     * 直播间创建
     * @param array $params
     * @return array
     * @throws ClientException
     */
    public function roomCreate(array $params)
    {
        //rtmp://rtmp.wanghongcheng.cn/live/101
        $max_id     =   LiveList::query()->max('Id');
        $live_id    =   $max_id + 1;
        $host_info  =   AnchorModel::where(['id' => $params['host_id'], 'is_delete' => 0])->select(['id', 'unique_id', 'nick_name'])->first();
        $live['CompanyId']  =   '621b9cc5-11b3-4d0e-ad82-981351e25336';
        $live['AppId']      =   '530defda-cb12-4d24-b0e8-dbfabb76393b';
        $live['HostId']     =   $host_info['unique_id'] ?? 0;
        $live['HostName']   =   $host_info['nick_name'] ?? '';
        $live['CreatedBy']  =   request()->post('admin_info')['user_id'] ?? 0;
        $live['Id']         =   $live_id;
        $live['_id']        =   $live_id;
        $live['Title']      =   $params['live_title'];
        $live['DuringTime'] =   0;
        $live['GoodsNum']   =   0;
        $live['PushUrl']    =   'rtmp://rtmp.wanghongcheng.cn/live/' . $live_id;
        $live['PushAddress']=   'rtmp://rtmp.wanghongcheng.cn/live/';
        $live['PushAuth']   =   $live_id;
        $live['Subscription']=  0;
        $live['ActualSubscription']=  0;
        $live['RTMPPullUrl']=  'rtmp://live.wanghongcheng.cn/live/' . $live_id;
        $live['FLVPullUrl'] =  'http://live.wanghongcheng.cn/live/' . $live_id . '.flv';
        $live['HLSPullUrl'] =  'http://live.wanghongcheng.cn/live/' . $live_id .'.m3u8';
        $live['AppName']    =  'live';
        $live['StreamName'] =  $live_id;
        $live['MainImg']    =  $params['main_img'];
        $live['StartTime']  =  0;
        $live['EndTime']    =  0;
        $live['Viewers']    =  0;
        $live['ActualViewers']  =  0;
//        $live['ProductIds']     =  '';
//        $live['VideoClips']     =  '';
        $live['Status']         =  0;
        $live['PubStatus']      =  LiveList::NORMAL_PUB;
        $live['StreamStatus']   =  0;
        $live['LastStreamUpdateTime']     =  Carbon::now()->toDateTimeString();
        $live['Desc']     =  $params['live_desc'];
        $live['Subscribed']     =  false;
//        $live['Statistics']     =  '';
//        $live['Tasks']          =  '';
        $live['PlanedStartTime']=  Carbon::parse($params['start_time'])->getPreciseTimestamp(3);
        $live['PlanedEndTime']  =  Carbon::parse($params['end_time'])->getPreciseTimestamp(3);
        $result     =   LiveList::insert($live);
        if ($result) {
            $this->roomNotify();
            return [true, '创建成功'];
        } else{
            return [false, '创建失败'];
        }
    }

    /**
     * 直播间修改
     * @param array $params
     * @param int $live_id
     * @return array
     */
    public function roomUpdate(array $params, int $live_id)
    {
        $host_info  =   AnchorModel::where(['id' => $params['host_id'], 'is_delete' => 0])->select(['id', 'unique_id', 'nick_name'])->first();
        $live['HostId']     =   $host_info['unique_id'] ?? 0;
        $live['HostName']   =   $host_info['nick_name'] ?? '';
        $live['CreatedBy']  =   request()->post('admin_info')['user_id'] ?? 0;
        $live['Title']      =   $params['live_title'];
        $live['MainImg']    =   $params['main_img'];
        $live['Desc']       =   $params['live_desc'];
        $live['PlanedStartTime']=  Carbon::parse($params['start_time'])->timestamp;
        $live['PlanedEndTime']  =  Carbon::parse($params['end_time'])->timestamp;
        $result     =   LiveList::where(['Id' => $live_id])->update($live);
        if ($result) {
            return [true, '修改成功'];
        } else{
            return [false, '修改失败'];
        }
    }

    /**
     * 直播间地址通知
     * @return array
     * @throws ClientException
     */
    public function roomNotify()
    {
        $wechat =   Config::get('upload');
        AlibabaCloud::accessKeyClient($wechat['ali_oss']['access_key_id'], $wechat['ali_oss']['access_key_secret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result =   AlibabaCloud::rpc()->product('live')->scheme('https')->action('AddLiveRecordNotifyConfig')        // https | http->version('2016-11-01')
            ->method('POST')->host('live.aliyuncs.com')->options([
                'query' => [
                    'RegionId'  =>  'cn-hangzhou',
                    'DomainName'=>  'live.wanghongcheng.cn',
                    'NotifyUrl' =>  'https://xcxapi.hzwhc.com/api/notify/live',
                    'Format'    =>  'JSON'
                ],
            ])
                ->request();
            if ($result->RequestId) {
                return [true, $result->RequestId];
            } else {
                return [false, '请求失败'];
            }
        } catch (ClientException $exception) {
            return [false, $exception->getMessage()];
        } catch (ServerException $exception) {
            return [false, $exception->getMessage()];
        }
    }

    /**
     * 直播间开播
     * @param int $room_id
     * @param int $start_type
     * @return array
     */
    public function roomStart(int $room_id, int $start_type = 1)
    {
        $pub_status =   LiveList::where(['Id' => $room_id])->value('Status');
        switch ($start_type) {
            case 1:             //开播
                $live_pub   =   1;
                break;

            case 2:             //关闭
                $live_pub   =   3;
                break;

            default:
                $live_pub   =   1;
                break;
        }

        if ($pub_status == $live_pub) {
            return [false, '操作错误'];
        }

        $result =   LiveList::where(['Id' => $room_id])->update(['Status' => $live_pub]);
        if ($result) {
            return [true, '操作成功'];
        } else {
            return [false, '操作失败'];
        }
    }


    public function roomData(int $room_id)
    {
        $client_service =   new ClientService();
        $alter_service  =   new AlterService();
        $anchor_service =   new AnchorLiveService();
        $operate_service=   new OperateService();
        //观看人数
        $watch_number   =   $client_service->getUserWatch($room_id);

        //观看次数
        $watch_time     =   $client_service->getVisitNum($room_id);

        //总订阅数
        $total_follow   =   $alter_service->totalFocus($room_id);

        //总订单数
        $total_orders   =   OrderModel::where(['live_id' => $room_id, 'is_pay' => OrderModel::IS_PAY])->count();

        //成交金额
        $total_price    =   OrderModel::where(['live_id' => $room_id, 'is_pay' => OrderModel::IS_PAY])->sum('total_price');

        //成交转换率

        //客单价

        //品单价

        /**
         * 查看商品成交数据
         */

    }
}
